package com.j4cf.auth.shiro.realm;

import com.j4cf.auth.dao.entity.AuthPermission;
import com.j4cf.auth.dao.entity.AuthRole;
import com.j4cf.auth.dao.entity.AuthUser;
import com.j4cf.auth.service.AuthApiService;
import com.j4cf.common.util.AESUtil;
import com.j4cf.common.util.MD5Util;
import com.j4cf.common.util.PropertiesFileUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户认证和授权
 */
public class AuthRealm extends AuthorizingRealm {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthRealm.class);

    @Autowired
    @Lazy
    private AuthApiService authApiService;

    /**
     * 授权：验证权限时调用
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
       // AuthUser authUser = authApiService.selectAuthUserByUsername(username);
        AuthUser authUser = authApiService.selectAuthUserByUsernameByCache(username);

        // 当前用户所有角色
        //List<AuthRole> authRoles = authApiService.selectAuthRoleByAuthUserId(authUser.getUserId());
        List<AuthRole> authRoles = authApiService.selectAuthRoleByAuthUserIdByCache(authUser.getUserId());
        Set<String> roles = new HashSet<>();
        for (AuthRole authRole : authRoles) {
            if (StringUtils.isNotBlank(authRole.getName())) {
                roles.add(authRole.getName());
            }
        }

        // 当前用户所有权限
        //List<AuthPermission> authPermissions = authApiService.selectAuthPermissionByAuthUserId(authUser.getUserId());
        List<AuthPermission> authPermissions = authApiService.selectAuthPermissionByAuthUserIdByCache(authUser.getUserId());
        Set<String> permissions = new HashSet<>();
        for (AuthPermission authPermission : authPermissions) {
            if (StringUtils.isNotBlank(authPermission.getPermissionValue())) {
                permissions.add(authPermission.getPermissionValue());
            }
        }

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(permissions);
        simpleAuthorizationInfo.setRoles(roles);
        return simpleAuthorizationInfo;
    }

    /**
     * 认证：登录时调用
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        // client无密认证
//        String authType = PropertiesFileUtil.getInstance("zheng-auth-client").get("zheng.auth.type");
//        if ("client".equals(authType)) {
//            return new SimpleAuthenticationInfo(username, password, getName());
//        }

        // 查询用户信息
        AuthUser authUser = authApiService.selectAuthUserByUsername(username);

        if (null == authUser) {
            throw new UnknownAccountException();
        }
        if (!authUser.getPassword().equals(MD5Util.md5(password + authUser.getSalt()))) {
            throw new IncorrectCredentialsException();
        }
        if (authUser.getLocked() == 1) {
            throw new LockedAccountException();
        }

        return new SimpleAuthenticationInfo(username, password, getName());
    }
}
